/**
 * DigestPostProcessingPlugin.java
 * 
 * FreeZzaph is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * FreeZzaph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.
 */
package freezzaph.plugins;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;

import freezzaph.exceptions.URLFetchException;
import freezzaph.plugins.util.Base64;
import freezzaph.plugins.util.URLFetcher;

/**
 * Plugin that computes the SHA-1 hash of all the files downloaded and
 * deletes the ones that match earlier computed hashes.
 * 
 * @author FreeZzaph
 */
public class DigestPostProcessorPlugin implements FreeZzaphPostProcessorPlugin {

	private static final File[] FILE_ARRAY_TEMPLATE = new File[0];

	/* (non-Javadoc)
	 * @see freezzaph.plugins.FreeZzaphPostProcessorPlugin#performPostProcessing(java.io.File[])
	 */
	public File[] performPostProcessing(File[] files) {
		ArrayList<File> acceptedFiles = new ArrayList<File>(files.length);
		HashMap<String, Object> hashes = new HashMap<String, Object>(files.length);
		
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			return files;
		}
		
		for (File file : files) {
			URL fileURL;
			try {
				 fileURL = file.toURI().toURL();
			} catch (MalformedURLException e) {
				continue;
			}
			
			byte[] fileBytes;
			try {
				fileBytes = URLFetcher.fetchBytes(fileURL).toByteArray();
			} catch (URLFetchException e) {
				continue;
			}
			byte[] digest = md.digest(fileBytes);
			String literalDigest = Base64.encodeToString(digest);
			
			if (!hashes.containsKey(literalDigest)) {
				hashes.put(literalDigest, null);
				acceptedFiles.add(file);
			} else {
				file.delete();
			}
		}
		
		// TODO Auto-generated method stub
		return acceptedFiles.toArray(FILE_ARRAY_TEMPLATE);
	}

	/* (non-Javadoc)
	 * @see freezzaph.plugins.FreeZzaphPlugin#getPluginName()
	 */
	public String getPluginName() {
		return "digest-duplicate-remover";
	}

	/*
	 * (non-Javadoc)
	 * @see freezzaph.plugins.FreeZzaphPostProcessorPlugin#getPluginDescription()
	 */
	public String getPluginAction() {
		return "Removing duplicates through the SHA-1 message digestion hash";
	}

}
